package controllers;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
/**
 * This class gives the option to send a new mail vis Gmail services.
 * @author Alon Shahaf
 * @Date 16.01.2013
 */	

public class SendMailSSL 
{
	public SendMailSSL()
	{

	}
	
	/**
	 * Sends a new mail using Gmail servers.
	 * @author Alon Shahaf
	 * @Date 16.01.2013
	 * @param to	the email address to send the mail to.
	 * @param subject	the subject of the mail.
	 * @param body	the message in the email.
	 */	
	public static void sendMail(String to, String subject, String body)
	{
		Properties 	props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");	
		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(OBLSettings.MAIL_USER,OBLSettings.MAIL_PASS);
					}
				});
		try 
		{	 
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(OBLSettings.MAIL_ADDR));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(to));
			message.setSubject(subject);
			message.setText(body);
 
			Transport.send(message);
		}
		catch (MessagingException e) 
		{
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * This class is the runnable mail thread
	 * @author Alon Shahaf
	 * @Date 16.01.2013
	 */	
	static class SendMailRunnable implements Runnable 
	{
		private String to;
		private String subject;
		private String body;

		/**
		 * Creates a new email runnable
		 * @author Alon Shahaf
		 * @Date 16.01.2013
		 * @param to	the email address to send the mail to.
		 * @param subject	the subject of the mail.
		 * @param body	the message in the email.
		 */			
		public SendMailRunnable(String to, String subject, String body)
		{
			this.to = to;
			this.subject = subject;
			this.body = body;
		}

		public void run() 
		{
			System.out.println("(SendMail) TO:"+to+" | SUBJECT="+subject);
			try
			{
				sendMail(to, subject, body);
			}
			catch (Exception e)
			{
				//e.printStackTrace(); 
			}
			//System.out.format("OK.\n");
		}
	}
}